<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <canvas width="960" height="500"></canvas>
    <script src="d3.v4.min.js"></script>
    <script>
        const nodes = d3.range(300).map((d,i)=>{
            return {
                index:i,
                color: i<150? "red":"brown"
            }
        })

        // console.log(nodes);
        // console.log(document);

        const canvas = document.querySelector("canvas")
        // console.log(canvas);
        const context = canvas.getContext("2d")
        // console.log(context);
        const width = canvas.width
        height = canvas.height  

        const simulation = d3.forceSimulation(nodes)
        .force('y',d3.forceY())
        .force("red",isolate(d3.forceX(-width / 6), function(d) { return d.color === "red"; }))//////////////
        .force("brown",isolate(d3.forceX(width / 6), function(d) { return d.color === "brown"; }))//////////////
        .force("charge",d3.forceManyBody().strength(-10))
        .on("tick",ticked)

        function ticked() {
            context.clearRect(0, 0, width, height);
            context.save();
            context.translate(width / 2, height / 2);
            nodes.forEach(drawNode);
            context.restore();///////////////
        }
        
        function drawNode(d) {
        context.beginPath();
        context.moveTo(d.x + 3, d.y);
        context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
        context.fillStyle = d.color;
        context.fill();
        }

        function isolate(force, filter) {
        var initialize = force.initialize;
        force.initialize = function() { initialize.call(force, nodes.filter(filter)); };
        return force;
        }
    </script>

</body>
</html>